import Vue from 'vue'
import Vuex from 'vuex'
import { getLogin } from '../request/api.js'
import router from '../router/index'
Vue.use(Vuex)
const state = {
  ruleForm: {
    user: '',
    pwd: ''
  },
  result: null,
  title: '',
  count: 0
}
const mutations = {
  increment(state, payload) {
    state.count += payload
  },

  setLogin(state, param) {
    state.result = param.result
  },
  setUser(state, n) {
    state.ruleForm.user = n
  },
  setPwd(state, n) {
    state.ruleForm.pwd = n
  }
}
const actions = {
  increment(content) {
    console.log('action.content', content)
    content.commit('increment')
  },
  getLogin(context) {
    getLogin().then(res => {
      console.log(res.data)
      context.commit('setLogin', {
        result: res.data
      })
      const len = res.data.length
      const userNameArr = []
      const passWordArr = []
      const ses = window.sessionStorage
      for (let i = 0; i < len; i++) {
        userNameArr.push(res.data[i].username)
        passWordArr.push(res.data[i].password)
      }
      if (userNameArr.indexOf(state.ruleForm.user) === -1) {
        window.alert('no account')
      } else {
        const index = userNameArr.indexOf(state.ruleForm.user)
        if (passWordArr[index] === state.ruleForm.pwd) {
          // 把token放在sessionStorage中
          ses.setItem('data', res.data[index].token)
          console.log(ses, 'ses')
          state.title = res.data[index].usertitle
          // 跳转到首页
          router.push('/')
        } else {
          window.alert('pass err')
        }
      }
    })
  },
  loginOut() {
    // 注销后 清除session信息 ，并返回登录页
    window.sessionStorage.removeItem('data')
    router.push('/login')
  }
}
export default new Vuex.Store({
  state,
  mutations,
  actions
})
